package cn.humaohua.study.yanmo_design_pattern.ch15.v3;

import java.util.ArrayList;
import java.util.List;

public class Composite extends Component {

    private List<Component> childComponents = null;

    private String name = "";

    public Composite(String name) {
        this.name = name;
    }

    @Override
    public void addChild(Component child) {
        if (childComponents == null)
            childComponents = new ArrayList<>();
        childComponents.add(child);

        //添加对父组件的引用
        child.setParent(this);
    }

    public void removeChild(Component child) {
        if (child != null) {
            int idx = childComponents.indexOf(child);
            if (idx != -1) {
                for (Component c : child.getChildren()) {
                    c.setParent(this);
                    childComponents.add(c);
                }
                childComponents.remove(child);
            }
        }
    }

    public List<Component> getChildren() {
        return childComponents;
    }

    @Override
    public void printStruct(String preStr) {
        System.out.println(preStr + "_" + this.name);
        if (this.childComponents != null) {
            preStr += " ";
            for (Component c : this.childComponents) {
                c.printStruct(preStr);
            }
        }
    }
}
